先做了一個簡易的文件創建頁面
doc_info/views.py
設定成用get載入http://127.0.0.1:8000/doc/create/
就顯示文件創建頁的表單
如果是post載入
就執行資料創建還有重新轉址到使用者個人文件頁
render: 是將資料從這個view傳送給指定的html然後呈現出來
從create的view裡面return render到 user list.html
跟從user list的view裡面return render到 user list.html 結果可能不一樣
因為個別view裡面傳送出去的資訊可能不同
redirect: 等於是重新載入特定網址
此處doc_id不用指定因為會自行創建
@login_required
def doc_create(request):
if request.method == "POST":
user_id = request.user.id
doc_create_date = datetime.now()
doc_title = request.POST.get('title','')
doc_remark = request.POST.get('remark','')
upload_file = request.FILES.get('upload_file','')
doc = doc_warehouse(
create_date = doc_create_date,
user_id = user_id,
title = doc_title,
remark = doc_remark,
upload_file = upload_file,
)
doc.save()
user_profile = get_object_or_404(UserProfile, user=request.user)
user_profile.phone_number = request.POST.get('phone_number','')
user_profile.save()
return redirect('/doc/user/list')
else:
user = request.user
Doc_warehouse = doc_warehouse.objects.filter(user_id=user.id)
form = CreateForm()
context = {
'form': form
}
return render(request, 'doc/create.html', context)
網址就一樣簡單明瞭
doc_info/urls.py
urlpatterns = [
path('doc/create/', views.doc_create, name='create'),
]
action保持"",在summit後會傳送回本頁
在測試的時候可以改成{% url 'doc_info:test' %}傳送到test將request的資訊都列出來
如果使用者有手機就列出手機
沒有手機就強制他一定要輸入手機 送出資料後會存到使用者profile
templates/create.html
{% block content %}
<a href="{% url 'doc_info:main' %}">Main page</a> |
<a href="{% url 'auth_info:profile' %}">My Profile</a> |
<a href="{% url 'account_logout' %}">Logout</a>
<form method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
<h3>Create Document</h3>
<table>
<tr>
<th>Author: </th>
<td>{{ user.first_name }} {{ user.last_name }}</td>
</tr>
<tr>
<th>Contact Email: </th>
<td>{{ user.email }}</td>
</tr>
{% if user.userprofile.phone_number %}
<tr>
<th>Contact Phone: </th>
<td>{{ user.userprofile.phone_number }}</td>
</tr>
{% else %}
<tr>
<th>Contact Phone: </th>
<td>{{ form.phone_number }}</td>
</tr>
{% endif %}
<!-- need to have some gap here -->
<tr>
<th>Title: </th>
<td>{{ form.title }}</td>
</tr>
<tr>
<th>Remark: </th>
<td>{{ form.remark }}</td>
</tr>
<tr>
<th>Attachment: </th>
<td><input type="file" name="upload_file"></td>
</tr>
</table>
<div class="button-wrapper submit">
<input type="submit" value="Save" />
</div>
</form>
{% endblock %}